package com.bawei.mall.product.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.DateUtils;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.common.rabbit.domain.Message;
import com.bawei.common.rabbit.enums.QueueEnum;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.MallProductRuleInfo;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.product.domain.model.ProductModel;
import com.bawei.mall.product.domain.model.SkuModel;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.domain.request.ProductInfoRequest;
import com.bawei.mall.product.service.IMallProductRuleInfoService;
import com.bawei.mall.product.service.IMallProductSkuInfoService;
import com.bawei.mall.product.service.IMallProductTypeInfoService;
import com.bawei.system.domain.vo.EsDocDelVo;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.remote.api.RemoteEsDocService;
import com.bawei.system.remote.api.RemoteEsIndexService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import com.bawei.mall.product.mapper.MallProductInfoMapper;
import com.bawei.mall.product.domain.MallProductInfo;
import com.bawei.mall.product.service.IMallProductInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;

/**
 * 商品信息Service业务层处理
 *
 * @author DongZeLiang
 * @date 2022-09-19
 */
@Service
@Slf4j
public class MallProductInfoServiceImpl implements IMallProductInfoService {

    @Autowired
    private MallProductInfoMapper mallProductInfoMapper;

    @Autowired
    private IMallProductSkuInfoService skuInfoService;

    @Autowired
    private IMallProductRuleInfoService ruleInfoService;


    @Autowired
    private ProductInfoCache productInfoCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RemoteEsDocService remoteEsDocService;

    @Autowired
    private RemoteEsIndexService remoteEsIndexService;

    @Autowired
    private IMallProductTypeInfoService mallProductTypeInfoService;

    public static final String INDEX_NAME="add_index";

    /**
     * 项目启动时，把商品数据初始化到ES中
     */
    @PostConstruct
    public void init() {
        loadingProductInfoToEs();
    }

    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ProductInfoResponse selectMallProductInfoById(Long id) {
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        ProductInfoResponse productInfoResponse = new ProductInfoResponse();
        BeanUtils.copyBeanProp(productInfoResponse, mallProductInfo);
        productInfoResponse.setSkuInfoList(
                skuInfoService.selectMallProductSkuInfoList(new MallProductSkuInfo() {{
                    setProductId(id);
                }})
        );
        return productInfoResponse;
    }

    @Override
    public ProductDetailsResponse selectProductDetailsById(Long productId) {
        if (productId == null || productId == 0) {
            throw new ServiceException("查询商品信息，依据不合法！");
        }
        ProductDetailsResponse productDetailsResponse = new ProductDetailsResponse();
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(productId);
        if (productModel == null) {
            throw new ServiceException("查询商品信息，商品数据为空");
        }
        productDetailsResponse.setProduct(productModel);
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);
        if (mallProductSkuInfos == null || mallProductSkuInfos.size() == 0) {
            throw new ServiceException("查询商品信息，SKU数据为空");
        }
        productDetailsResponse.setSkuList(mallProductSkuInfos);
        MallProductRuleInfo ruleInfo = ruleInfoService.selectMallProductRuleInfoById(productModel.getRuleId());
        if (ruleInfo == null) {
            throw new ServiceException("查询商品信息，规格数据为空");
        }
        productDetailsResponse.setProductRule(ruleInfo);
        return productDetailsResponse;
    }

    /**
     * 查询商品信息列表
     *
     * @param mallProductInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<MallProductInfo> selectMallProductInfoList(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoList(mallProductInfo);
    }

    /**
     * 新增商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setCreateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest);
        if (i == 0) {
            return i;
        }

        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );

        // 给搜索系统发送消息需要进行搜索更新
        try {
            rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                    Message.builderMsg(productInfoRequest.getId()));
        } catch (ServiceException serviceException) {
            throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
        }
        return i;
    }

    /**
     * 修改商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.updateMallProductInfo(productInfoRequest);
        if (i == 0) {
            //将商品信息推送至MQ，异步更新ES
            try {
                rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                        Message.builderMsg(productInfoRequest.getId()));
            } catch (ServiceException serviceException) {
                throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
            }
            return i;
        }
        skuInfoService.deleteMallProductSkuInfoByProductId(productInfoRequest.getId());
        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );
        return i;
    }

    /**
     * 批量删除商品信息
     *
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoByIds(Long[] ids) {
        skuInfoService.deleteMallProductSkuInfoByProductIds(ids);
        for (Long id : ids) {
            // 延迟执行
            productInfoCache.delayRemove(id);
        }
        return mallProductInfoMapper.deleteMallProductInfoByIds(ids);
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoById(Long id) {
        return mallProductInfoMapper.deleteMallProductInfoById(id);
    }

    /**
     * 商品总条数
     *
     * @param mallProductInfo 商品查询
     * @return
     */
    @Override
    public Long selectMallProductInfoCount(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
    }

    /**
     * 修改上架商品
     *
     * @param id
     * @param isUpload
     * @return
     */
    @Override
    public void uploadInfo(Long id, Integer isUpload) {
        // 参数校验
        if(id==null){
            throw new RuntimeException("参数"+id+"不能为空");
        }
        // 查询商品SPU信息
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        if(mallProductInfo==null){
            throw new RuntimeException("商品id"+id+"不存在");
        }
        Long productId = mallProductInfo.getId();
        // 查询商品skuinfos 商品的sku
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);

        if(CollectionUtils.isEmpty(mallProductSkuInfos)){
            throw new RuntimeException("改商品id"+id+"下不存在sku信息");
        }
        // 修改上架状态
        skuInfoService.updateStart(id,isUpload);
        // 参数转换
        List<EsDocInsertVo> esDocInsertVo = transForData(mallProductInfo,mallProductSkuInfos);
        remoteEsDocService.batchInsertDocs(esDocInsertVo);
    }

    // 参数转换
    private List<EsDocInsertVo> transForData(MallProductInfo mallProductInfo, List<MallProductSkuInfo> mallProductSkuInfos) {
        // 构建返回结果集
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        //创建索引
        R<Boolean> indexCreate = remoteEsIndexService.indexCreate(INDEX_NAME);
        mallProductSkuInfos.forEach(mallProductSkuInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();

            //TODO product_info要提取为全局变量
            esDocInsertVo.setIndexName(INDEX_NAME);
            esDocInsertVo.setTypeName("_doc");
            // TODO 待补全data信息
            esDocInsertVo.setId(String.valueOf(mallProductSkuInfo.getId()));
            //map.put("name",mallProductInfo.getName());
            //map.put("productDesc",mallProductInfo.getProductDesc());
            map.put("type",mallProductInfo.getType());
            // 值转换
            map.put("typeName",mallProductTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getType())).getName());

            //字典值转换
            String status = mallProductInfo.getStatus();
            String getstatus = getstatus("sys_is_del", Integer.valueOf(status));
            map.put("status", getstatus);

            //上下架状态改变
            Integer productStatus = mallProductInfo.getIsUpload();
            String producted = productStatus("is_upload", productStatus);
            map.put("isUpload", producted);

            map.put("typeIds",mallProductInfo.getTypeIds());
            //map.put("img",mallProductInfo.getImg());
            //map.put("carouselImages",mallProductInfo.getCarouselImages());
            map.put("commentCount",mallProductInfo.getCommentCount());
            map.put("collectCount",mallProductInfo.getCollectCount());
            map.put("brand",mallProductInfo.getBrand());
            map.put("unit",mallProductInfo.getUnit());
            //map.put("keywords",mallProductInfo.getKeywords());
            map.put("ruleId",mallProductInfo.getRuleId());
            map.put("revision",mallProductInfo.getRevision());

            //存储的值为商品标题、描述、关键字等
            ArrayList<String> arrayList = new ArrayList<>();
            arrayList.add(mallProductInfo.getProductDesc());
            arrayList.add(mallProductInfo.getKeywords());
            arrayList.add(mallProductInfo.getName());
            map.put("suggestions",arrayList);

            map.put("productId",mallProductSkuInfo.getProductId());
            map.put("sku",mallProductSkuInfo.getSku());
            map.put("stock",mallProductSkuInfo.getStock());
            map.put("price",mallProductSkuInfo.getPrice());
            map.put("purchasePrice",mallProductSkuInfo.getPurchasePrice());
            map.put("sellingPrice",mallProductSkuInfo.getSellingPrice());
            //map.put("image",mallProductSkuInfo.getImage());
            map.put("number",mallProductSkuInfo.getNumber());
            map.put("weight",mallProductSkuInfo.getWeight());
            map.put("volume",mallProductSkuInfo.getVolume());

            // 完成商品图片集的保存与查询
            List<String> strings = new ArrayList<>();
            if(mallProductInfo.getImg()!=null){
                strings.add(mallProductInfo.getImg());
            }
            strings.addAll(Arrays.asList(mallProductInfo.getCarouselImages().split(",")));
            map.put("images",strings);

            esDocInsertVo.setData(map);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }

    /**
     * 转换上下架字典值
     * @param isUpload
     * @param productStatus
     * @return
     */
    private String productStatus(String isUpload, Integer productStatus) {
        String typeproductStatus="";
        switch (productStatus){
            case 0:{
                typeproductStatus="未上架";
                break;
            }
            case 1:{
                typeproductStatus="已上架";
                break;
            }
            case 2:{
                typeproductStatus="已下架";
                break;
            }
            case 3:{
                typeproductStatus="上架失败";
                break;
            }
            default: throw new ServiceException("转化异常");
        }
        return typeproductStatus;
    }

    /**
     * 转化商品状态字典值
     * @param sysIsDel
     * @param status
     * @return
     */
    private String getstatus(String sysIsDel, Integer status) {
        String typeStatus="";
        switch (status){
            case 0:{
                typeStatus="隐藏";
                break;
            }
            case 1:{
                typeStatus="显示";
                break;
            }
            default: throw new ServiceException("转化异常");
        }
        return typeStatus;
    }

    @Override
    public void loadingProductInfoToEs() {
        //查询所有商品信息
        List<MallProductInfo> mallProductInfos = mallProductInfoMapper.selectMallProductInfoList(new MallProductInfo());
        if (mallProductInfos == null || mallProductInfos.size() == 0) {
            log.info("暂无需要同步的商品");
        }
        //调用ES查询索引是否存在
        R<Boolean> indexExit = remoteEsIndexService.indexExit("mall_product");
        if (!indexExit.getData()) {
            log.info("mall_product索引不存在,调用ES服务创建索引");
            //创建索引
            R<Boolean> indexCreate = remoteEsIndexService.indexCreate("mall_product");
            if (!indexCreate.getData()) {
                log.info("创建mall_product索引失败");
            }
            //批量同步商品信息到ES
            //构建参数
            List<EsDocInsertVo> esDocInsertVo = builderProductInfoToEs(mallProductInfos);
            //调用ES服务批量插入文档
            R<Boolean> batchInsert = remoteEsDocService.batchInsertDocs(esDocInsertVo);
            if (batchInsert.getData()) {
                log.info("批量同步商品信息到ES成功");
            }
        }
    }

    /**
     * 修改下架商品
     */
    @Override
    public void downStart(Long id, Integer isUpload) {
        // 参数校验
        if(id==null){
            throw new RuntimeException("参数"+id+"不能为空");
        }
        try {
            // 创建
            EsDocDelVo esDocDelVo = new EsDocDelVo();
            esDocDelVo.setIndexName(INDEX_NAME);
            esDocDelVo.setDelFileName("productId");
            esDocDelVo.setDelFileValue(Long.valueOf(id));
            // 远程调用 调用ES服务删除文档
            remoteEsIndexService.indexdel(esDocDelVo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 修改数据库状态
        skuInfoService.downdateStart(id,isUpload);
    }

    private List<EsDocInsertVo> builderProductInfoToEs(List<MallProductInfo> mallProductInfos) {
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        mallProductInfos.stream().forEach(mallProductInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(String.valueOf(mallProductInfo.getId()));
            esDocInsertVo.setIndexName("mall_product");
            //对象转为Map
            Map<String, Object> data = JSON.parseObject(JSON.toJSONString(mallProductInfo), Map.class);
            esDocInsertVo.setData(data);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }
}
